package com.jckl.foodathon.fragments;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;

import com.jckl.foodathon.R;
import com.jckl.foodathon.common.constant.CommunicationConstants;
import com.jckl.foodathon.model.Blogger;
import com.jckl.foodathon.services.config.EditBloggerConfiguration;
import com.jckl.foodathon.services.config.GetAllBloggerInfo;
import com.jckl.foodathon.services.config.NewBloggerConfiguration;
import com.jckl.foodathon.sqlite.dao.DaoSession;
import com.jckl.foodathon.sqlite.model.TB_Blogger;
import com.jckl.foodathon.sqlite.services.BloggerRepository;
import com.jckl.foodathon.sqlite.services.SqliteCommon;

public class BloggerFragment extends Fragment implements OnClickListener, OnItemSelectedListener{
	
	//Screen input
	Spinner bloggerEdit;
	EditText name;
	EditText url;
	EditText author;
	ImageButton blogImage;
	
	Button save;
	Button refresh;
	Blogger blogger;
	Bitmap bloggerImage;
	
	List<String> bloggers = new ArrayList<String>();
	List<TB_Blogger> sqlite_bloggers = new ArrayList<TB_Blogger>();
	
	boolean isSave = true;
	
	private final int SELECT_PHOTO = 1;
	
	public BloggerFragment () {
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_blogger, container, false);
		
		bloggerEdit	= (Spinner) view.findViewById(R.id.blogger_edit);
		save		= (Button) view.findViewById(R.id.btn_blogger_save);
		refresh 	= (Button) view.findViewById(R.id.btn_blogger_refresh);
		blogImage	= (ImageButton) view.findViewById(R.id.imgbtn_blogger_image);
		
		bloggerEdit.setOnItemSelectedListener(this);
		save.setOnClickListener(this);
		refresh.setOnClickListener(this);;
		blogImage.setOnClickListener(this);
		
		
		name			= (EditText) view.findViewById(R.id.blogger_name);
		url 			= (EditText) view.findViewById(R.id.blogger_url);
		author			= (EditText) view.findViewById(R.id.blogger_author);
		
		// Elements from sqlite
		SqliteCommon sqliteCommon = new SqliteCommon();
		DaoSession session = sqliteCommon.setupDatabase(getActivity().getApplicationContext());
		sqlite_bloggers = BloggerRepository.getAllBloggers(session);
		
		// Spinner blogger elements
		bloggers.add(getResources().getString(R.string.none));
		for (TB_Blogger tb_blogger : sqlite_bloggers) {
			bloggers.add(tb_blogger.getName());
		}
		ArrayAdapter<String> bloggerAdapter = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_spinner_item, bloggers);
		bloggerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		bloggerEdit.setAdapter(bloggerAdapter);
		
		return view;
	}

	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.btn_blogger_save:
			if(isSave){
				saveStoreData();
			}else{
				editStoreData();
			}
			break;
		case R.id.imgbtn_blogger_image:
			pickImage();
			break;
		case R.id.btn_blogger_refresh:
			refreshBloggerList();
			break;
		}
	}
	
	private void setDataToObject(){
		blogger = new Blogger();
		blogger.setName(name.getText().toString());
		blogger.setAuthor(author.getText().toString());
		blogger.setBlogURL((url.getText().toString()));
		blogger.setImage(bloggerImage);
		blogger.setActive(true);
	}

	private void saveStoreData(){
		setDataToObject();
		NewBloggerConfiguration bloggerConfig = new NewBloggerConfiguration();
		bloggerConfig.perform(getActivity(), blogger);
	}
	
	private void editStoreData(){
		setDataToObject();
		EditBloggerConfiguration bloggerConfig = new EditBloggerConfiguration();
		bloggerConfig.perform(getActivity(), blogger);
	}
	
	private void pickImage(){
		 Intent photoPickerIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
         photoPickerIntent.setType("image/*");
         photoPickerIntent.putExtra("crop", "true");
         photoPickerIntent.putExtra("scale", true);
         photoPickerIntent.putExtra("outputX", getActivity().getResources().getDimension(R.dimen.img_blogger_width));
         photoPickerIntent.putExtra("outputY", getActivity().getResources().getDimension(R.dimen.img_blogger_height));
         photoPickerIntent.putExtra("aspectX", 1);
         photoPickerIntent.putExtra("aspectY", 1);
         
         startActivityForResult(photoPickerIntent, SELECT_PHOTO);
	}
	
    @Override
	public void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) { 
        super.onActivityResult(requestCode, resultCode, imageReturnedIntent); 
 
        switch(requestCode) { 
        case SELECT_PHOTO:
            if(resultCode == Activity.RESULT_OK){
            	final Bundle extras =  imageReturnedIntent.getExtras();
            	if(extras != null){
            		bloggerImage = extras.getParcelable("data");
            		blogImage.setImageBitmap(bloggerImage);
            	}
            }
        }
    }
    
    private void refreshBloggerList(){
		//Refresh the brand info into sqlite
		GetAllBloggerInfo bloggerInfo = new GetAllBloggerInfo();
		bloggerInfo.perform(getActivity());
    }

	@Override
	public void onItemSelected(AdapterView<?> ParentView, View view, int position, long id) {
		String bloggerName = bloggers.get(position);
		
		//Check the selection is not 'none'
		if(bloggerName.equals(getActivity().getResources().getString(R.string.none))){
			isSave = true;
			save.setText(getActivity().getResources().getString(R.string.btn_blog_save));
			name.setEnabled(true);
		}else{
			for (TB_Blogger tb_blogger: sqlite_bloggers) {
				if(tb_blogger.getName().equals(bloggerName)){
					name.setText(tb_blogger.getName());
					author.setText(tb_blogger.getAurthor());
					url.setText(tb_blogger.getBlogURL());
					
					if(tb_blogger.getImage() != null){
						try{
							blogImage.setImageBitmap(BitmapFactory.decodeByteArray(tb_blogger.getImage(), 0, tb_blogger.getImage().length));
						}catch (Exception ex){
							Log.e(CommunicationConstants.APP_TAG, "Bitmap failed to decode");
						}
					}else{
						blogImage.setImageBitmap(null);
					}
					
					save.setText(getActivity().getResources().getString(R.string.btn_blogger_edit));
					name.setEnabled(false);
					isSave = false;
				}
			}
		}
		
	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub
		
	}
}
